package com.katze.common.ws.core;

import com.katze.common.ws.handler.JwtAuthHandler;
import com.katze.common.ws.protocol.Message;
import com.katze.common.ws.protocol.MessageType;
import io.netty.channel.Channel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MessageDispatcher {

    private final Map<MessageType, MessageChannel> handlers = new ConcurrentHashMap<>();

    private final JwtAuthHandler jwtAuthHandler;

    public MessageDispatcher(JwtAuthHandler jwtAuthHandler) {
        this.jwtAuthHandler = jwtAuthHandler;
    }

    public void registerHandler(MessageType type, MessageChannel handler) {
        handlers.put(type, handler);
    }

    public void dispatch(Channel channel, Message message) throws Exception{
        MessageChannel handler = handlers.get(message.getType());
        if (handler != null) {
            handler.onMessage(channel, message);
        } else {
            throw new UnsupportedOperationException("未知消息类别: " + message.getType());
        }
    }

    public void close(Channel channel) throws Exception{
//        MessageType type = channel.attr(UserChannelGroup.TYPE).get();
//        MessageChannel handler = handlers.get(type);
//        if (handler != null) {
//            handler.onClose(channel);
//        } else {
//            throw new UnsupportedOperationException("未知消息类别: " + type);
//        }
        for (MessageChannel item : handlers.values()) {
            item.onClose(channel);
        }
    }

    public JwtAuthHandler getJwtAuthHandler() {
        return jwtAuthHandler;
    }
}
